<template>
    <div class="repair-task-progress-layout">
        <div class="divide-line-part"></div>
        <div v-if="isShowBDMapState" id="idBaiDuMap" class="biadu-map-part"></div>
        <div v-if="isShowBDMapState" class="baidu-distance-part">
            <p>{{userName}}</p>
            <div v-if="distance>0">
                <p v-if="(distance/1000)>1">距报修位置{{(distance/1000).toFixed(1)}}千米</p>
                <p v-else>距报修位置{{distance}}米</p>
            </div>
            <p v-else>不在当前范围内</p>
        </div>
        <yd-timeline>
            <yd-infinitescroll :callback="loadList" ref="infinitescrollDemo">
                <div slot="list">
                    <yd-timeline-item v-if="item.state!=='01'&&item.state!=='97'"  v-for="(item,index) in progressList">
                        <div>
                            <div v-if="item.state==='20'" class="task-progress-content-part">
                                <span class="title-part">配件更换请求</span>
                                <span class="gray-tint-color">{{item.created}}</span>
                            </div>
                            <div v-else-if="item.state==='21'" class="task-progress-content-part">
                                <span class="title-part">同意更换配件</span>
                                <span class="gray-tint-color">{{item.created}}</span>
                            </div>
                            <div v-else-if="item.state==='22'" class="task-progress-parts-part">
                                <div class="task-progress-parts-content-part">
                                    <span class="title-part">拒绝更换配件</span>
                                    <span class="gray-tint-color">{{item.created}}</span>
                                </div>
                                <span class="gray-tint-color" style="text-align: left">{{item.name}}</span>
                            </div>
                            <div v-else class="task-progress-content-part">
                                <span class="title-part">{{item.stateNm}}</span>
                                <span class="gray-tint-color">{{item.created}}</span>
                            </div>
                            <div v-if="item.state==='02'" class="task-progress-people-part">
                                <span class="blue-color">{{item.name}}</span>
                                <!--<i v-show="isCanShowPhone" @click="telHandlerClick(item.mobile)" slot="icon" class="iconfont icon-dianhua1 blue-color"></i>-->
                                <img v-show="isCanShowPhone" @click="telHandlerClick(item.mobile)" slot="icon" src="../../assets/icon-dianhua1.png" class="phone-logo-part">
                            </div>
                            <p v-if="item.general_uuid!==null&&item.state==='20'"
                               style="text-align: left"
                               class="blue-color" @click="replaceHandler(item.general_uuid)">详情</p>
                            <p v-if="item.state==='02'&&progressList[0].state==='02'" style="text-align: left" class="gray-tint-color">{{'预计处理时间:'+item.evaluated_start_time}}</p>
                            <p v-if="item.state==='05'" style="text-align: left" class="gray-tint-color">{{item.content}}</p>
                            <p v-if="item.state==='05'" style="text-align: left" class="gray-tint-color">{{'预计处理时间:'+item.evaluated_start_time}}</p>
                            <p v-if="item.state==='08'&&item.type_name!==null" style="text-align: left" class="gray-tint-color">{{'['+item.type_name+']'+item.content}}</p>
                            <p v-if="item.state==='09'" style="text-align: left" class="gray-tint-color">{{'['+item.stateNm+']'+item.content}}</p>
                            <p v-if="item.state==='21'" style="text-align: left" class="gray-tint-color">{{item.name}}</p>
                        </div>
                    </yd-timeline-item>
                </div>
                <span slot="doneTip"></span>
            </yd-infinitescroll>
        </yd-timeline>

        <div style="height: 1.4rem"></div>

        <div class="task-operation-part buttom-tabbar">
            <!--撤销按钮-->
            <a  href="javascript:;"
                @click="retreatHandleClick"
                v-show="isCanCloseRetreat"
                class="weui-btn weui-btn_primary horizontal-part">撤销</a>
            <!--完成按钮-->
            <a  href="javascript:;"
                @click="confirmHandleClick"
                v-show="isCanCloseTask"
                class="weui-btn weui-btn_primary horizontal-part">完成</a>
            <!--评价按钮-->
            <a  href="javascript:;"
                @click="evaluateHandleClick"
                v-show="isCanCloseEvaluate"
                class="weui-btn weui-btn_primary horizontal-part">评价</a>
        </div>

        <yd-popup v-model="isShowEvaluateDialog" position="bottom" height="70%">
            <div class="mui-flex">
                <div class="cell">
                    <img :src="qn_domain+headUrl" class="img-logo" alt=""  @click="show1 = true"
                         size="large">
                </div>
                <div class="cell4">
                    <p class="center-name">{{userName}}</p>
                </div>
            </div>
            <yd-cell-item>
                <span slot="left">专业技能</span>
                <yd-rate slot="right" v-model="jineng" :showText="['很差','较差','一般','较好','很好']"></yd-rate>
            </yd-cell-item>
            <yd-cell-item>
                <span slot="left">响应速度</span>
                <yd-rate slot="right" v-model="sudu" :showText="['很差','较差','一般','较好','很好']"></yd-rate>
            </yd-cell-item>
            <yd-cell-item>
                <span slot="left">服务态度</span>
                <yd-rate slot="right" v-model="fuwu" :showText="['很差','较差','一般','较好','很好']"></yd-rate>
            </yd-cell-item>
            <div class="small-space-background"></div>
            <yd-cell-item>
                <yd-textarea slot="right" placeholder="详细评价" maxlength="200" v-model="desContent"></yd-textarea>
            </yd-cell-item>
            <div class="small-space-background"></div>
            <div class="evaluate-dialog-part" style="background-color:#f3f8f8">
                <yd-button size="large" type="primary" @click.native="repairEvaluateClick" style="background-color:#3cc8a8;color:white;height: 50px">确定</yd-button>
            </div>
        </yd-popup>

    </div>
</template>

<script>
    import {getProLocation,orderStateFlow,canCloseWarningOrder,orderCancel,closeByUser,getProInfoFromOrder,sendEvaluate} from "../../pcof/post";
    import {userInfoData,bdLatitude,bdLongitude,qn_domain,keepSamePageState} from '../../globalVariables'
    export default {
        name: "repairTaskProgress",
        data() {
            return {
                isShowBDMapState: false,
                //评价头像Url
                headUrl: '',
                //评价用户名称
                userName: '',
                //七牛Url
                qn_domain: '',
                progressList: [],
                //报修单UUid
                taskUUid: '',
                //报修单状态
                taskState: '',
                page: 1,
                pageSize: 20,
                serviceTotalPage: 1,
                //控制撤销按钮
                isCanCloseRetreat: false,
                //控制关闭按钮
                isCanCloseTask: false,
                //控制评价按钮
                isCanCloseEvaluate: false,
                //控制显示评价Dialog
                isShowEvaluateDialog: false,
                //专业技能
                jineng: 1,
                //响应速度
                sudu: 1,
                //服务态度
                fuwu: 1,
                //评价内容
                desContent: '',
                distance: 0,
                instLatitude: 0,
                instLongitude: 0,
                proLatitude: '',
                proLongitude: '',
                isCanShowPhone: true,
            }
        },
        async created() {
            //接受上个页面传值 在实例创建完成后被立即调用
            this.taskUUid = this.$route.params.taskUUid;
            this.taskState = this.$route.params.taskState;
            this.isShowEvaluateDialog = this.$route.params.isShowEvaluateDialog;

            //报修机构的地理位置
            this.instLatitude = localStorage.getItem(bdLatitude); // 纬度，浮点数，范围为90 ~ -90
            this.instLongitude = localStorage.getItem(bdLongitude); // 经度，浮点数，范围为180 ~ -180。
            console.log(this.instLatitude);
            console.log(this.instLongitude);

            if (this.taskState === '97' || this.taskState === '98' || this.taskState === '99') {
                this.isCanShowPhone = false;
            } else {
                this.isCanShowPhone = true;
            }

            this.$dialog.loading.open('加载中...');
            var response = await orderStateFlow(
                JSON.parse(localStorage.getItem(userInfoData)).mobile,
                this.taskUUid,
                1,
                20);
            if (response.data.code === 200) {
                this.$dialog.loading.close();
                this.progressList = response.data.data.list;
                if (this.progressList[0].state === '02' || this.progressList[0].state === '04'
                    || this.progressList[0].state === '06' || this.progressList[0].state === '22'
                    || this.progressList[0].state === '20'|| this.progressList[0].state === '21') {
                    this.isShowBDMapState = true;
                }
                this.serviceTotalPage = response.data.data.totalPage;
                if (this.serviceTotalPage > 1) {
                    this.page++;
                } else {
                    /* 所有数据加载完毕 */
                    this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.loadedDone');
                }
            } else {
                this.$dialog.loading.close();
                this.$dialog.toast({
                    mes: response.data.msg,
                    timeout: 1500
                });
            }

            this.canCloseWarningOrderFunc();
            // this.initTaskButton(this.taskState);
            this.initTaskButton(this.progressList[0].state);
            this.qn_domain = localStorage.getItem(qn_domain);
            //获取该任务下运维任务信息
            this.getProInfoFromOrderFunc();
        },
        mounted () {
            // this.showBaiDuMapFunc();
        },
        methods: {
            initTaskButton(state) {
                //待评价
                if (state === '98' || state === '08') {
                    this.isCanCloseEvaluate = true;
                    // this.getProInfoFromOrderFunc();
                }
                //ToBeAllocation("00", "待分配");ToBeTakeOrder("01", "待接单");ToBeProcessed("02", "待处理");
                else if (state === '00' || state === '01' || state === '02') {
                    this.isCanCloseRetreat = true;
                }
                //InProcess("04", "处理中");Suspending("06", "挂起中");
                else if (state === '04' || state === '06') {
                    this.isCanCloseRetreat = false;
                }
            },
            async canCloseWarningOrderFunc() {
                var response = await canCloseWarningOrder(JSON.parse(localStorage.getItem(userInfoData)).mobile);
                if (response.data.code === 200) {
                    if (response.data.data.can === '1') {
                        if (this.taskState === '99'
                            || this.taskState === '98'
                            || this.taskState === '97'
                            || this.progressList[0].state === '99'
                            || this.progressList[0].state === '98'
                            || this.progressList[0].state === '97'
                            || this.progressList[0].state === '08') {
                            this.isCanCloseTask = false;
                        } else {
                            this.isCanCloseTask = true;
                        }
                    } else {
                        this.isCanCloseTask = false;
                    }
                }
            },
            showBaiDuMapFunc() {
                let that = this;
                var map;
                if (this.instLatitude === null || this.instLatitude === ''
                    || this.instLongitude === null || this.instLongitude === ''
                    || this.proLatitude === null || this.proLatitude === ''
                    || this.proLongitude === null || this.proLongitude === '' ) {
                    this.distance = 0;
                } else {
                    // 百度地图API功能
                    // 创建Map实例
                    //报修单位置
                    map = new BMap.Map("idBaiDuMap", {enableMapClick: true});
                    // 初始化地图,设置中心点坐标和地图级别
                    var point = new BMap.Point(parseFloat(this.instLongitude), parseFloat(this.instLatitude));
                    map.centerAndZoom(point, 13);
                    // 添加地图类型控件
                    map.addControl(new BMap.MapTypeControl());
                    // // 创建标注
                    var marker = new BMap.Marker(point);
                    map.addOverlay(marker);

                    // var myCompOverlay = new ComplexCustomOverlay(point);
                    // map.addOverlay(myCompOverlay);//将标注添加到地图中

                    function ComplexCustomOverlay(point) {
                        this._point = point;
                    };

                    ComplexCustomOverlay.prototype = new BMap.Overlay();
                    ComplexCustomOverlay.prototype.initialize = function(map){
                        this._map = map;
                        var div = this._div = document.createElement("div");
                        div.style.position = "absolute";
                        div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);//聚合功能?
                        // 可以根据参数设置元素外观
                        // div.style.width="0.8rem";
                        // div.style.height = "0.6rem";
                        var arrow = this._arrow = document.createElement("img");
                        if (that.headUrl === null || that.headUrl === '' || that.headUrl === undefined) {
                            arrow.src = require('../../assets/ic_avatar_default.png');
                        } else {
                            arrow.src = that.qn_domain+that.headUrl;
                        }
                        arrow.style.width = "0.6rem";
                        arrow.style.height = "0.6rem";
                        arrow.style.top = "22px";
                        arrow.style.left = "22px";
                        arrow.style.borderRadius = "0.6rem";
                        arrow.style.objectFit = "cover";
                        div.appendChild(arrow);
                        map.getPanes().markerPane.appendChild(div);//getPanes(),返回值:MapPane,返回地图覆盖物容器列表  labelPane呢???
                        return div;
                    };

                    ComplexCustomOverlay.prototype.draw = function(){
                        var map = this._map;
                        var pixel = map.pointToOverlayPixel(this._point);
                        this._div.style.left = pixel.x - parseInt(this._arrow.style.left) + "px";
                        this._div.style.top  = pixel.y - 30 + "px";
                    };

                    //多点标记
                    var secondpoint = new BMap.Point(parseFloat(this.proLongitude), parseFloat(this.proLatitude));
                    map.centerAndZoom(secondpoint, 13);
                    // 添加地图类型控件
                    map.addControl(new BMap.MapTypeControl());
                    // 创建标注
                    // var secondmarker = new BMap.Marker(secondpoint);
                    // map.addOverlay(secondmarker);
                    var myCompOverlay = new ComplexCustomOverlay(secondpoint);
                    map.addOverlay(myCompOverlay);//将标注添加到地图中
                    console.log(point);
                    console.log(secondpoint);
                    that.distance = parseInt(map.getDistance(point,secondpoint));

                    //获取报修人当前的位置
                    // wx.ready(function () {
                    //     wx.getLocation({
                    //         type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                    //         success: function (res) {
                    //             var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                    //             var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                    //             var speed = res.speed; // 速度，以米/每秒计
                    //             var accuracy = res.accuracy; // 位置精度
                    //
                    //             //多点标记
                    //             var secondpoint = new BMap.Point(longitude, latitude);
                    //             map.centerAndZoom(secondpoint, 13);
                    //             // 添加地图类型控件
                    //             map.addControl(new BMap.MapTypeControl());
                    //             // 创建标注
                    //             var secondmarker = new BMap.Marker(secondpoint);
                    //             map.addOverlay(secondmarker);
                    //             // var myCompOverlay = new ComplexCustomOverlay(secondpoint);
                    //             // map.addOverlay(myCompOverlay);//将标注添加到地图中
                    //
                    //             that.distance = map.getDistance(point,secondpoint)*1.0;
                    //             console.log(that.distance);
                    //         }
                    //     });
                    // });
                }
            },
            async loadList() {
                if (this.page > 1) {
                    var response = await orderStateFlow(
                        JSON.parse(localStorage.getItem(userInfoData)).mobile,
                        this.taskUUid,
                        this.page,
                        this.pageSize);
                    if (response.data.code === 200) {
                        const _list = response.data.data.list;
                        this.progressList = [...this.progressList, ..._list];
                        if (_list.length < this.pageSize || this.page === this.serviceTotalPage) {
                            /* 所有数据加载完毕 */
                            this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.loadedDone');
                            return;
                        }
                        /* 单次请求数据完毕 */
                        this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.finishLoad');

                        this.page++;

                    } else {

                    }
                } else {
                    /* 所有数据加载完毕 */
                    this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.loadedDone');
                }
            },
            replaceHandler(general_uuid) {
                localStorage.setItem(keepSamePageState,'returnTaskProgress');
                this.$router.push({
                    name: 'repairReplaceParts',
                    params: {
                        generalUuid: general_uuid,
                        taskUUid: this.taskUUid,
                        taskState: this.progressList[0].state
                    }
                })
            },
            retreatHandleClick() {
                this.$dialog.confirm({
                    title: '',
                    mes: '是否撤销本次报修？',
                    opts: () => {
                        this.$dialog.loading.open('加载中...');
                        this.orderCancelFunc();
                    }
                });
            },
            confirmHandleClick() {
                this.$dialog.confirm({
                    title: '',
                    mes: '直接标记完成，该条报修单将无法记录维修细节？',
                    opts: () => {
                        this.$dialog.loading.open('加载中...');
                        this.closeByUserFunc();
                    }
                });
            },
            async repairEvaluateClick() {
                var response = await sendEvaluate(
                    JSON.parse(localStorage.getItem(userInfoData)).mobile,
                    this.taskUUid,
                    this.jineng*2,
                    this.sudu*2,
                    this.fuwu*2,
                    JSON.parse(localStorage.getItem(userInfoData)).uuid,
                    this.desContent
                );
                if (response.data.code === 200) {
                    this.$router.back();
                } else {
                    this.$dialog.toast({
                        mes: response.data.msg,
                        timeout: 1500
                    });
                }
            },
            evaluateHandleClick() {
                this.isShowEvaluateDialog = true;
            },
            async getProLocationFunc(uuid) {
                var response = await getProLocation(uuid);
                if (response.data.code === 200) {
                    this.proLatitude = response.data.data.latitude;
                    this.proLongitude = response.data.data.longitude;
                    if (this.isShowBDMapState) {
                        this.showBaiDuMapFunc();
                    }
                }
            },
            async getProInfoFromOrderFunc() {
                var response = await getProInfoFromOrder(
                    JSON.parse(localStorage.getItem(userInfoData)).mobile,
                    this.taskUUid,
                );
                if (response.data.code === 200) {
                    this.headUrl = response.data.data.head_image_url;
                    this.userName = response.data.data.name;
                    this.getProLocationFunc(response.data.data.uuid);
                } else {
                    this.$dialog.toast({
                        mes: response.data.msg,
                        timeout: 1500
                    });
                }
            },
            async orderCancelFunc() {
                var response = await orderCancel(
                    JSON.parse(localStorage.getItem(userInfoData)).mobile,
                    this.taskUUid,
                );
                if (response.data.code === 200) {
                    this.$dialog.loading.close();
                    this.$router.back();
                } else {
                    this.$dialog.loading.close();
                    this.$dialog.toast({
                        mes: response.data.msg,
                        timeout: 1500
                    });
                }
            },
            async closeByUserFunc() {
                var response = await closeByUser(
                    JSON.parse(localStorage.getItem(userInfoData)).mobile,
                    this.taskUUid,
                );
                if (response.data.code === 200) {
                    this.$dialog.loading.close();
                    this.$router.back();
                } else {
                    this.$dialog.loading.close();
                    this.$dialog.toast({
                        mes: response.data.msg,
                        timeout: 1500
                    });
                }
            },
            telHandlerClick(number) {
                window.location.href = 'tel://'+number;
            }
        },
    }
</script>

<style lang="scss">
    .repair-task-progress-layout {
        /*padding-top: 1rem;*/
        margin-top: 1rem;
        .task-progress-content-part {
            display: flex;
            justify-content: space-between;

            .title-part {
                font-size: 1.2em;
                color: #0d0d0d
            }
        }

        .task-progress-parts-part {
            display: flex;
            flex-direction: column;

            .task-progress-parts-content-part {
                display: flex;
                align-items: center;
                justify-content: space-between;
            }

            .title-part {
                font-size: 1.2em;
                color: #0d0d0d
            }
        }

        .task-progress-people-part {
            display: flex;
            padding-top: 0.2rem;

            .iconfont {
                font-size: 0.3rem;
                padding-left: 0.1rem;
            }

            .phone-logo-part {
                width: 0.3rem;
                height: 0.3rem;
                margin-left: 0.1rem;
            }
        }

        .biadu-map-part {
            width: 100%;
            height: 4rem;
        }

        .baidu-distance-part {
            display: flex;
            justify-content: space-between;
            padding-left: 0.4rem;
            padding-right: 0.4rem;
            padding-top: 0.2rem;
        }

        .task-operation-part {
            padding-top: 0.3rem;
            padding-bottom: 0.3rem;
            display: flex;
            z-index:200;
            background: #fafafa;

            .horizontal-part {
                margin: 0 auto;
                width: 40%;
            }

            .weui-btn {
                display: flex;
                height: 0.6rem;
                align-items: center;
                justify-content: center;
                font-size: 1.2em;
            }
        }
    }
</style>